<?php

namespace App\Http\Controllers\Admin\Arts\Setup;

use App\Http\Controllers\Admin\ParentController;
use App\Master\Framework\Extend\Module as FrameworkModule;
use App\Models\Admin\Framework\AdminSetupModel;
use App\Utils\AppResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PageController extends ParentController
{

    public function __construct(array $attributes = [])
    {
        parent::__construct();
    }

    public function index(Request $request, $__table = '')
    {
        return view ('admin.arts.setup.page.'.$__table);
    }

    /**
     * 获取单页信息
     * @param Request $request
     * @return string|void
     */
    public function getSetup(Request $request){
        if($request->isMethod ('post')) {
            $__table = $request->input('__table');
            return AppResult::response200('success',FrameworkModule::_SetupModule($__table));
        }
    }

    /**
     * 单页信息更新
     * @param Request $request
     * @return string|void
     */
    public function updateSetup(Request $request){
        if($request->isMethod ('post')) {
            if(!$_table = $request->__table)
            {
                return AppResult::response201('数据编辑失败，请稍后再试！');
            }

            $params = $request->all();

            unset($params['__table'], $params['s']);

            foreach ($params as $key => $val)
            {
                $params[$key] = ($val === 'null' || $val === null) ? '' : $val;
            }

            $params = json_encode($params, JSON_UNESCAPED_UNICODE);

            if(AdminSetupModel::query()->where('table', $_table)->exists())
            {
                AdminSetupModel::query()->where('table', $_table)->update(['value'=>$params]);
            } else {
                AdminSetupModel::query()->where('table', $_table)->insert(['table'=>$_table, 'value'=>$params]);
            }

            Cache::forget("ADMIN_SETUP_{$_table}");

            unset($_table, $params);

            return AppResult::response200('数据编辑成功！');
        }
    }
}